﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.Assert;
using CommunitySystem.Ctrls;
using CommunitySystem.EmpbasicService;
using CommunitySystem.PublicOfficialSelectionService;
using CommunitySystem.Views;
using EHR.Common;

namespace CommunitySystem
{
    public partial class ShenPiControl4 : AsyncCtrl, IReturnListenerc
    {
        #region IReturnListenerc 成员
        public void BeginReturn()
        {
            //Load();
        }
        #endregion
        public NavMoveSwitch Nav { get; set; }
        private PublicOfficialSelectionServiceClient Client = new PublicOfficialSelectionServiceClient();
        public ObservableCollection<RenQianQueRen> models = new ObservableCollection<RenQianQueRen>();
        private EmpbasicService.EmpBasicServiceClient Client2 = new EmpbasicService.EmpBasicServiceClient();
        public int OrgID = 0;
        private string OrgName = "";
        private ObservableCollection<RenQianGongShi> _renqimodels = null;
        private bool _isls = false;
        public ShenPiControl4(int orgID, string orgName, ObservableCollection<RenQianGongShi> models, bool isls)
        {
            InitializeComponent();
            _isls = isls;
            _renqimodels = models;
            OrgID = orgID;
            OrgName = orgName;
            Client2.GetBianZhiDetailModelCompleted += new EventHandler<EmpbasicService.GetBianZhiDetailModelCompletedEventArgs>(Client2_GetBianZhiDetailModelCompleted);
            if(Session.LoginUser.LoginName == "admin")
            {
                //OKButton.Visibility = System.Windows.Visibility.Collapsed;
                shenqing.Visibility = System.Windows.Visibility.Collapsed;
                queren.Visibility = System.Windows.Visibility.Visible;
                scrol.IsEnabled = false;
            }
            else
            {
                ////OKButton.Visibility = System.Windows.Visibility.Visible;
                shenqing.Visibility = System.Windows.Visibility.Visible;
                queren.IsEnabled = false;
                //queren.Visibility = System.Windows.Visibility.Collapsed;
                scrol.IsEnabled = true;
            }
            if (_isls) queren.IsEnabled = false;
            Loaded();
        }

        

        public void Loaded()
        {
            //Client.GetRenQianGongShiCompleted -= new EventHandler<GetRenQianGongShiCompletedEventArgs>(Client_GetRenQianGongShiCompleted);
            //Client.GetRenQianGongShiCompleted += new EventHandler<GetRenQianGongShiCompletedEventArgs>(Client_GetRenQianGongShiCompleted);
            //Client.GetRenQianGongShiAsync(OrgID);
            Client.GetRenQianQueRenCompleted += new EventHandler<GetRenQianQueRenCompletedEventArgs>(Client_GetRenQianQueRenCompleted);
            Client.GetRenQianQueRenCompleted += new EventHandler<GetRenQianQueRenCompletedEventArgs>(Client_GetRenQianQueRenCompleted);
            Client.GetRenQianQueRenAsync(OrgID);
        }

     
        void Client_GetRenQianQueRenCompleted(object sender, GetRenQianQueRenCompletedEventArgs e)
        {
            stackpanel.Children.Clear();
            if (e.Result != null && e.Result.Count > 0)
            {
                if (e.Result[0].ID != 0) shenqing.IsEnabled = true;
                if (e.Result[0].ID != 0 && Session.LoginUser.LoginName == "admin"&&!_isls) queren.Visibility = System.Windows.Visibility.Visible;
                //OKButton.IsEnabled = true;
                models = e.Result;
                int count = ((ObservableCollection<RenQianQueRen>)e.Result).Count;

                StackPanel sp = null;
                for (int i = 0; i < count; i++)
                {
                    StackPanel s = new StackPanel();
                    s.Margin = new Thickness(5, 5, 5, 5);
                    s.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                    s.Orientation = Orientation.Horizontal;

                    if (e.Result[i].DutyAttribute == "领导职务")
                    {
                        TextBlock tb7 = new TextBlock();
                        tb7.Text = "  " + e.Result[i].EmpName + "同志任命为" + e.Result[i].Department_Duty + " " + e.Result[i].Duty + "    任期自";
                        tb7.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        tb7.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        s.Children.Add(tb7);


                        DatePicker dp1 = new DatePicker();
                        if (!string.IsNullOrEmpty(e.Result[0].StartDate.ToString())) dp1.SelectedDate = e.Result[i].StartDate;
                        dp1.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        dp1.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        Binding b3 = new Binding();
                        b3.Source = e.Result[i];
                        b3.Path = new PropertyPath("StartDate");
                        b3.Mode = BindingMode.TwoWay;
                        BindingOperations.SetBinding(dp1, DatePicker.SelectedDateProperty, b3);
                        s.Children.Add(dp1);

                        TextBlock tb4 = new TextBlock();
                        tb4.Text = "至";
                        tb4.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        tb4.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        s.Children.Add(tb4);


                        DatePicker dp2 = new DatePicker();
                        if (!string.IsNullOrEmpty(e.Result[0].EndDate.ToString())) dp2.SelectedDate = e.Result[i].EndDate;
                        dp2.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        dp2.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        Binding b31 = new Binding();
                        b31.Source = e.Result[i];
                        b31.Path = new PropertyPath("EndDate");
                        b31.Mode = BindingMode.TwoWay;
                        BindingOperations.SetBinding(dp2, DatePicker.SelectedDateProperty, b31);
                        s.Children.Add(dp2);

                        TextBlock tb41 = new TextBlock();
                        tb41.Text = "   其中试用期";
                        tb41.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        tb41.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        s.Children.Add(tb41);

                        TextBox t1s = new TextBox();
                        t1s.Tag = i;
                        t1s.TextChanged += new TextChangedEventHandler(TextBox_TextChanged);
                        if (!string.IsNullOrEmpty(e.Result[i].SYQ.ToString())) t1s.Text = e.Result[i].SYQ.ToString();
                        t1s.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        t1s.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        t1s.Width = 60;
                        t1s.Height = 25;
                        Binding b2s = new Binding();
                        b2s.Source = e.Result[i];
                        b2s.Path = new PropertyPath("SYQ");
                        b2s.Mode = BindingMode.TwoWay;
                        BindingOperations.SetBinding(t1s, TextBox.TextProperty, b2s);
                        s.Children.Add(t1s);


                        TextBlock tb411 = new TextBlock();
                        tb411.Text = "年";
                        tb411.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        tb411.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        s.Children.Add(tb411);

                        sp = new StackPanel();
                        sp.Orientation = Orientation.Horizontal;
                        sp.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    else if (e.Result[i].DutyAttribute == "非领导职务")
                    {
                        TextBlock tb7 = new TextBlock();
                        tb7.Text = "  " + e.Result[i].EmpName + "同志任命为" + e.Result[i].Department_Duty + " " + e.Result[i].Duty + "    任命自";
                        tb7.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        tb7.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        s.Children.Add(tb7);


                        DatePicker dp1 = new DatePicker();
                        if (!string.IsNullOrEmpty(e.Result[0].StartDate.ToString())) dp1.SelectedDate = e.Result[i].StartDate;
                        dp1.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        dp1.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        Binding b3 = new Binding();
                        b3.Source = e.Result[i];
                        b3.Path = new PropertyPath("StartDate");
                        b3.Mode = BindingMode.TwoWay;
                        BindingOperations.SetBinding(dp1, DatePicker.SelectedDateProperty, b3);
                        s.Children.Add(dp1);

                        TextBlock tb4 = new TextBlock();
                        tb4.Text = "起";
                        tb4.VerticalAlignment = System.Windows.VerticalAlignment.Center;
                        tb4.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
                        s.Children.Add(tb4);



                        sp = new StackPanel();
                        sp.Orientation = Orientation.Horizontal;
                        sp.Visibility = System.Windows.Visibility.Collapsed;
                    }

                    stackpanel.Children.Add(s);
                    stackpanel.Children.Add(sp);
                }
            }
            else { shenqing.IsEnabled = false; queren.IsEnabled = false; }
        }

        void cb1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
       
            ((RenQianGongShi) ((ComboBox) sender).Tag).ISTongyi = ((System.Windows.Controls.ContentControl)
                                                                  (((ComboBoxItem) ((ComboBox) sender).SelectedItem))).
                Content.
                ToString();
     
        }

        private string pattern = @"^[0-9]+([.]{1}[0-9]+){0,1}$";
        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            Match m = Regex.Match(((TextBox)sender).Text, pattern);   // 匹配正则表达式
            if (!string.IsNullOrEmpty(((TextBox)sender).Text))
            {
                if (!m.Success)   // 输入的不是数字
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("只能输入数字！");
                    ((TextBox)sender).Text = "";
                    return;
                    //((TextBox)sender).Text = param1;   // textBox内容不变

                    // 将光标定位到文本框的最后
                    //((TextBox)sender).SelectionStart = ((TextBox)sender).Text.Length;
                }
              
            }
            

        }

        private Dictionary<ComboBox, StackPanel> dic = new Dictionary<ComboBox,StackPanel>();
        void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ((RenQianGongShi)((ComboBox)sender).Tag).IsFanYing = ((System.Windows.Controls.ContentControl)
                                                                  (((ComboBoxItem)((ComboBox)sender).SelectedItem))).
                Content.
                ToString();
            if (dic.Keys.Contains(((ComboBox)sender)))
            if(((ComboBox)sender).SelectedIndex == 1)
            {
                dic[((ComboBox) sender)].Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                dic[((ComboBox)sender)].Visibility = System.Windows.Visibility.Collapsed;
            }

            #region

            #endregion
        }

        private int c = 0;
      
       private bool Validate()
        {
            if (models != null && models.Count > 0)
            {
               
                foreach (var item in models)
                {
                    if (item.DutyAttribute == "领导职务")
                    {
                        if (item.StartDate == null || item.EndDate == null)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage(item.EmpName + "确认转任时间不能为空!");
                            return false;
                        }
                        if (item.StartDate > item.EndDate)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage(item.EmpName + "结束时间不能早于开始时间!");
                            return false;
                        }
                    }
                    if (item.DutyAttribute == "非领导职务")
                    {
                        if (item.StartDate == null)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage(item.EmpName + "确认转任时间不能为空!");
                            return false;
                        }
                      
                    }
                    foreach (var item1 in _renqimodels.Where(p => p.EmpName == item.EmpName).ToList())
                    {
                        if (item1.EndDate > item.StartDate)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage(item.EmpName + "确认转任的开始时间不能早于公示的结束时间!");
                            return false;
                        }
                    }
                }
            }
            else
            {
                return false;
            }
            return true;
        }
        private void shenqing_Click(object sender, RoutedEventArgs e)
        {
           
            if (Validate())
            {
                if (MessageBox.Show("确定申请转任吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    foreach (RenQianQueRen item in models)
                    {
                        if (string.IsNullOrEmpty(item.SYQ.ToString())) item.SYQ = 0;
                        Client.InsertRenQianQueRenCompleted -= new EventHandler<InsertRenQianQueRenCompletedEventArgs>(Client_InsertRenQianQueRenCompleted);

                        Client.InsertRenQianQueRenCompleted += new EventHandler<InsertRenQianQueRenCompletedEventArgs>(Client_InsertRenQianQueRenCompleted);
                        Client.InsertRenQianQueRenAsync(item);
                        c += 1;
                    }
                }
            }
        }

        void Client_InsertRenQianQueRenCompleted(object sender, InsertRenQianQueRenCompletedEventArgs e)
        {
            if (c == models.Count)
            {
                c = c - 1;
                string ss = "";
                foreach (RenQianQueRen i in models)
                {
                    ss += i.PublicOfficialRecordID.ToString() + ",";
                }
                Client.QueRenShenQingZhuanRenCompleted -= new EventHandler<QueRenShenQingZhuanRenCompletedEventArgs>(Client_QueRenShenQingZhuanRenCompleted);
                Client.QueRenShenQingZhuanRenCompleted += new EventHandler<QueRenShenQingZhuanRenCompletedEventArgs>(Client_QueRenShenQingZhuanRenCompleted);
                Client.QueRenShenQingZhuanRenAsync(ss.Substring(0, ss.Length - 1));
            }
        }

        void Client_QueRenShenQingZhuanRenCompleted(object sender, QueRenShenQingZhuanRenCompletedEventArgs e)
        {
            if(e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("申请成功！");
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("请完整填写任前管理信息！"); 
            }
        }

        private void queren_Click(object sender, RoutedEventArgs e)
        {
            Client2.GetBianZhiDetailModelAsync(OrgID.ToString(), "");
            
        }
        public ObservableCollection<BianZhiModel> BianZhiModels = new ObservableCollection<BianZhiModel>();
        void Client2_GetBianZhiDetailModelCompleted(object sender, EmpbasicService.GetBianZhiDetailModelCompletedEventArgs e)
        {
            BianZhiModels = e.Result;
            string weichenggong = "";
            if (BianZhiModels != null && BianZhiModels.Count > 0)
            {
                foreach(BianZhiModel b in BianZhiModels)
                {
                    if (models.Where(p => p.Department_Duty == b.JiGouMingCheng && p.DutyAttribute == "领导职务" && p.DutyLevel == "乡科级正职（主任科员）").Count() >
                        Convert.ToInt32(!string.IsNullOrEmpty(b.ZhengKeShiJi) ? Convert.ToInt32(b.ZhengKeShiJi) : 0))
                        weichenggong += b.JiGouMingCheng + "-正科" + ",";
                    if (models.Where(p => p.Department_Duty == b.JiGouMingCheng && p.DutyAttribute == "领导职务" && p.DutyLevel == "乡科级副职（副主任科员）").Count() >
                        Convert.ToInt32(!string.IsNullOrEmpty(b.FuKeShiJi) ? Convert.ToInt32(b.FuKeShiJi) : 0))
                        weichenggong += b.JiGouMingCheng + "-副科" + ",";
                    if (models.Where(p => p.Department_Duty == b.JiGouMingCheng && p.DutyAttribute == "非领导职务" && p.DutyLevel == "乡科级正职（主任科员）").Count() >
                        Convert.ToInt32(!string.IsNullOrEmpty(b.ZhuRenShiJi) ? Convert.ToInt32(b.ZhuRenShiJi) : 0))
                        weichenggong += b.JiGouMingCheng + "-主任科员" + ",";
                    if (models.Where(p => p.Department_Duty == b.JiGouMingCheng && p.DutyAttribute == "非领导职务" && p.DutyLevel == "乡科级副职（副主任科员）").Count() >
                        Convert.ToInt32(!string.IsNullOrEmpty(b.FuZhuRenShiJi) ? Convert.ToInt32(b.FuZhuRenShiJi) : 0))
                        weichenggong += b.JiGouMingCheng + "-副主任科员" + ",";
                }
                if(!string.IsNullOrEmpty(weichenggong))
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("以下科室职数不足：" +
                                                                      weichenggong.Substring(0, weichenggong.Length - 1));
                }
                else
                {
                    if (MessageBox.Show("确定转任吗？", "提示", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                    {
                        foreach (RenQianQueRen i in models)
                        {
                            if (i.IsZhuanRen == true)
                            {
                                SilverlightMessageBoxLibrary.Message.ErrorMessage("已转任，不可重复操作！");
                                return;
                            }
                        }
                        foreach (RenQianQueRen i in models)
                        {
                            Client.QueRenZhuanRenCompleted -= new EventHandler<QueRenZhuanRenCompletedEventArgs>(Client_QueRenZhuanRenCompleted);
                            Client.QueRenZhuanRenCompleted += new EventHandler<QueRenZhuanRenCompletedEventArgs>(Client_QueRenZhuanRenCompleted);
                            Client.QueRenZhuanRenAsync(i.PublicOfficialRecordID);
                            cd += 1;
                        }
                    }
                }
                //foreach(RenQianQueRen i in models)
                //{
                //    if(BianZhiModels.Where(p=>p.OrgID == OrgID && p.JiGouMingCheng == i.Department_Duty))
                //}
            }
        }

        private int cd = 0;
        void Client_QueRenZhuanRenCompleted(object sender, QueRenZhuanRenCompletedEventArgs e)
        {
            if (cd == models.Count)
            {
                cd = cd - 1;
                SilverlightMessageBoxLibrary.Message.InfoMessage("确认转任成功！");
            }
        }
    }
}
